package com.stars.util.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		applicationContext = context;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		if(exist(name)){
			return (T) applicationContext.getBean(name);
		}

		return null;
	}
	
	public static boolean exist(String name){
		return applicationContext.containsBean(name) ;
	}

	public static <T> T getBean(Class<T> cls) throws BeansException {
		return applicationContext.getBean(cls);
	}

}
